package cn.bellychang.leetcode.question203.cl02recursion;

import com.google.common.base.Joiner;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: bellychang
 * @date: 2020/2/13
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    ListNode(int[] array) {
        if (Objects.isNull(array) || array.length == 0) {
            throw new IllegalArgumentException();
        }
        this.val = array[0];
        ListNode current = this;
        for (int i = 1; i < array.length; i++) {
            current.next = new ListNode(array[i]);
            current = current.next;
        }
    }

    @Override
    public String toString() {
        List<Integer> list = new ArrayList<>();
        ListNode temp = this;
        while (temp != null) {
            list.add(temp.val);
            temp = temp.next;
        }
        return Joiner.on("->").join(list);
    }
}

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            // solve the most basic question
            return null;
        } else {
            // convert original question to a smaller one
            if (head.val == val) {
                // 如果头节点需要删除，那么我们原问题的结果就是这个更短的红色的链表
                return removeElements(head.next, val);
            }else{
                // 如果头节点不需要删除，那么我们原问题的结果就是头节点link上这个更短的红色的链表
                ListNode listNode = removeElements(head.next, val);
                head.next = listNode;
                return head;
            }
        }
    }
}
